<template>
  <div style="height: calc(100vh - 120px)">
    <!--  -->
    <crumbs @goBack="() => {}" :superiorMenu="['报表统计']" currentMenu="库存水位预警表" style="margin-bottom: 12px">
      <span slot="content">
        <div class="topSearch">
          <a-form-model ref="ruleForm" layout="inline" :model="filterForm">
            <a-form-model-item label="预警类型">
              <a-select v-model="filterForm.type" @change="changeGetList" defaultValue="0">
                <a-select-option value="0">库存不足</a-select-option>
                <a-select-option value="1">库存超量</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-button @click="handleShowFilter" style="margin-top: 4px" icon="filter"
              >筛选 <span class="filter-num" style="margin-left: 5px">{{ ' ' + filteredNums }}</span></a-button
            >
          </a-form-model>
        </div>
      </span>
    </crumbs>
    <!-- 头部模块 -->
    <a-card :bordered="false">
      <div class="topBox">
        <div class="itemBox" v-for="(item, index) in topArray" :key="index">
          <div class="rightBox">
            <div class="rightBot">{{ item.title }}</div>
            <div class="rightTop">{{ item.number }}</div>
          </div>
        </div>
      </div>
    </a-card>
    <div style="height: 12px; background: #f0f2f5"></div>

    <a-card :bordered="false" style="height: calc(100vh - 390px)">
      <!-- 操作按钮区域 -->
      <div class="table-operator right-btn">
        <a-button @click="showColumn" icon="unordered-list" style="margin-right: 10px"> 设置列 </a-button>
        <a-button @click="handleExport(selectedRows)" icon="upload" style="float: right" class="btns" v-if="hasButton('waterLevelReport:derive')">导出</a-button>
      </div>
      <div>
        <a-table
          row-key="goodsId"
          size="middle"
          :key="tableKey"
          :scroll="{ x: scrollX, y: 'calc(100vh - 520px)' }"
          :hideDefaultSelections="false"
          :columns="columns"
          :dataSource="modelList"
          :pagination="false"
          @change="tableChange"
          :row-selection="{ selectedRowKeys: selectedRowKeys, columnTitle: ' ', onChange: onSelectChange }"
          class="j-table-force-nowrap"
          :components="drag(columns, 'WATER_LEVEL_REPORT')"
        >
          <span slot="category" slot-scope="text, record">{{ record.categoryText }} </span>
          <span
            slot="goodsQualifiedNumTxt"
            :style="{ color: record.goodsQualifiedNum >= record.warningNum ? '#F25643' : '#00b042' }"
            slot-scope="text, record"
          >
            {{ text || '-' }}
          </span>
          <span slot="warningNumTxt" slot-scope="text, record"> {{ text || '-' }} </span>
          <span slot="goodsScrapNumTxt" slot-scope="text, record"> {{ text || '-' }} </span>

          <!-- 6个字符控制 超出。。。 -->
          <span :title="text" slot="serialName" slot-scope="text">
            {{ text }}
          </span>
          <span :title="text" slot="deviceCategoryText" slot-scope="text">
            {{ text }}
          </span>
          <span slot="actions" slot-scope="text, record">
            <span>
              <a @click="handleEdit(record)" href="#">编辑</a>
              <a-divider type="vertical" />
              <a-dropdown>
                <a class="ant-dropdown-link">
                  更多
                  <a-icon type="down" />
                </a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a-button type="link" @click="handleOpen(record, '0')" v-if="record.programStatus == '1'"
                      >启用
                    </a-button>
                    <a-button @click="handleOpen(record, '1')" type="link" v-else>禁用 </a-button>
                  </a-menu-item>
                  <a-menu-item>
                    <a-button type="link" @click="handleDelete(record)">删除</a-button>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </span>
          </span>
          <!-- 行信息 -->
          <span
            slot="serialNumber"
            :title="record.serialNumber"
            slot-scope="text, record"
            class="btn-text"
            @click="handleDetail(record)"
          >
            {{ record.serialNumber }}
          </span>
          <span slot="reporter" :title="record.reporterText" slot-scope="text, record">{{ record.reporterText }}</span>

          <span slot="amount" :title="commafyTofixed(record.amount, 2)" slot-scope="text, record">{{
            commafyTofixed(record.amount, 2)
          }}</span>
          <span slot="payAmount" :title="commafyTofixed(record.payAmount, 2)" slot-scope="text, record">{{
            commafyTofixed(record.payAmount, 2)
          }}</span>
          <span slot="unPayAmount" :title="commafyTofixed(record.unPayAmount, 2)" slot-scope="text, record">{{
            commafyTofixed(record.unPayAmount, 2)
          }}</span>
          <span
            slot="programStatusText"
            :title="text"
            slot-scope="text, record"
            :style="{ color: taskStatusCheck(record.programStatus) }"
            >{{ text }}</span
          >

          <!-- 输入框搜索 -->
          <div slot="searchInput" slot-scope="{ selectedKeys, confirm, clearFilters, column }" class="searchWorkOreder">
            <a-input
              placeholder="请输入"
              v-model="filterForm[column.dataIndex]"
              style="width: 188px; display: block"
              @pressEnter="handleSearch"
            />
            <a-button
              type="primary"
              style="width: 80px; margin-left: 20px; display: block"
              @click="() => handleSearch(selectedKeys, confirm, column.dataIndex, clearFilters)"
            >
              搜索
            </a-button>
          </div>
          <a-icon
            slot="searchIcon"
            slot-scope="filtered"
            type="search"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <!-- 选择搜索 -->
          <div slot="selectDropdown" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
            <a-tree-select
              v-if="column.dataIndex == 'category'"
              allow-clear
              v-model="filterForm[selectkeys(column.dataIndex)]"
              :multiple="false"
              placeholder="请选择"
              style="width: 200px"
              :tree-data="treeData"
              :replaceFields="replaceFields"
              :show-checked-strategy="SHOW_PARENT"
              search-placeholder="请选择"
              @change="treeChange"
            />
            <a-select
              mode="multiple"
              placeholder="请选择"
              style="width: 200px"
              v-model="filterForm.serialProperties"
              v-if="column.dataIndex == 'serialProperties'"
            >
              <a-select-option v-for="item in serialPropertiesList" :key="item.value" :value="item.value">
                {{ item.label }}
              </a-select-option>
            </a-select>
            <a-button
              type="primary"
              style="width: 80px; margin-left: 20px; display: block"
              @click="() => handleSearch(confirm, column.dataIndex, clearFilters)"
            >
              搜索
            </a-button>
          </div>
          <!-- 选择搜索 -->
          <div slot="selectDropdownSingle" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
            <a-select
              placeholder="请选择"
              allowClear
              style="width: 188px"
              v-model="filterForm[selectkeys(column.dataIndex)]"
              @change="(v) => changeSelect(v, selectkeys(column.dataIndex))"
            >
              <a-select-option
                v-for="(item, i) in selectOptions(column.dataIndex)"
                :key="i"
                :value="item[column.selectValue]"
                >{{ item[column.selectText] }}</a-select-option
              >
            </a-select>
            <a-button
              type="primary"
              style="width: 80px; margin-left: 20px; display: block"
              @click="() => handleSearch(confirm, column.dataIndex, clearFilters)"
            >
              搜索
            </a-button>
          </div>
          <a-icon
            slot="selectIcon"
            slot-scope="filtered"
            type="filter"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
          <!-- 日期搜索 -->
          <div slot="datePicker" slot-scope="{ confirm, clearFilters, column }" class="searchWorkOreder">
            <a-range-picker
              style="width: 188px"
              v-model="dateForm[column.dataIndex]"
              format="YYYY-MM-DD"
              :placeholder="['开始时间', '结束时间']"
              @change="(v) => onOk(v, column.dataIndex)"
            />
            <a-button
              type="primary"
              style="width: 80px; margin-left: 20px; display: block"
              @click="() => handleSearch(confirm, column.dataIndex, clearFilters)"
            >
              搜索
            </a-button>
          </div>
          <a-icon
            slot="dateIcon"
            slot-scope="filtered"
            type="filter"
            :style="{ color: filtered ? '#108ee9' : undefined }"
          />
        </a-table>
      </div>
      <SetColumn
        columnName="设置列"
        ref="SetColumn"
        v-if="showSetColumn"
        @sureBtn="sureBtn"
        @cancelBtn="showSetColumn = false"
      />
    </a-card>
    <a-drawer placement="right" width="500" :visible="showFilter" @close="closeFilter">
      <div class="filter-body">
        <div slot="title" class="uni-card filter-tit">
          筛选 <span class="filter-num">{{ filteredNums }}</span>
        </div>
        <div class="uni-card" v-if="filteredNums > 0" style="background: #fff">
          <div v-for="(item, i) in filteredList" :key="i" v-show="item.text" class="tag-wrap">
            <span class="filter-tag" @click="delFiltered(item.key)">
              <span class="tag-text">{{ `${item.title}：${item.text}` }}</span>
              <a-icon type="close" style="float: right" />
            </span>
          </div>
        </div>
        <div style="overflow-y: scroll; flex: 1; padding: 0">
          <div class="uni-card" style="background: #fff">
            <a-form-model ref="ruleForm" layout="vertical" :model="filterForm">
              <a-form-model-item label="物品编号">
                <a-input v-model="filterForm.serialNumber" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="物品名称">
                <a-input v-model="filterForm.serialName" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="规格">
                <a-input v-model="filterForm.serialSpecifications" placeholder="请输入" />
              </a-form-model-item>
              <a-form-model-item label="物品属性">
                <a-select mode="multiple" placeholder="请选择" v-model="filterForm.serialProperties">
                  <a-select-option v-for="item in serialPropertiesList" :key="item.value" :value="item.value">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-form-model-item label="创建日期">
                <a-range-picker
                  :allowClear="true"
                  v-model="filterForm['createTime']"
                  style="width: 100%"
                  :disabled-date="disabledStartDate"
                  @change="(v) => onOk(v)"
                />
                <!-- <a-month-picker
                  :allowClear="false"
                  style="width: 100%"
                  v-model="inOutDate"
                  placeholder="选择月份"
                  @change="(v) => onOk(v, 'inOutDate')"
                  :defaultValue="now"
                  :disabled-date="disabledStartDate"
                /> -->
              </a-form-model-item>
              <a-form-model-item label="预警类型">
                <a-select v-model="filterForm.type" @change="changeGetList" defaultValue="0">
                  <a-select-option value="0">库存不足</a-select-option>
                  <a-select-option value="1">库存超量</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-form-model>
          </div>
        </div>
        <div class="footer-submit">
          <a-button class="margin-btn" @click="resetFilter">重置</a-button>
          <a-button type="primary" @click="handleFilter">确定</a-button>
        </div>
      </div>
    </a-drawer>
    <!-- 全选/分页 -->
    <div class="uni-card pagination-contian" :style="{ left: collapsed ? '199px' : '70px' }">
      <div style="display: inline-block" :style="{ marginLeft: collapsed ? '24px' : '37px' }">
        <a-checkbox :indeterminate="listIndeterminate" :checked="listCheckAll" @change="onCheckAllChange"></a-checkbox>
        <span style="margin-left: 8px">
          {{ `已选 ${selectedRowKeys.length}/${total} 项` }}
          <span @click="clearArr" class="pubColor" style="margin: 0 10px">清空</span>
        </span>
      </div>
      <div style="display: inline-block; float: right">
        <a-pagination
          :total="total"
          v-model="current"
          :page-size-options="pageSizeOptions"
          :page-size="pageSize"
          @change="onChangePage"
          @showSizeChange="onShowSizeChange"
          show-quick-jumper
          show-size-changer
        />
      </div>
    </div>
    <a-modal style="width: 50%" v-model="selectExportVisiable" title="导出">
      <template slot="footer">
        <a-button key="back" @click="handleExportAll"> 导出全部数据 </a-button>
        <a-button key="submit" type="primary" @click="handleSelectExport"> 导出选中数据 </a-button>
      </template>
      {{ selectExportTitle }}
    </a-modal>
    <goodsManagementDetail ref="goodsManagementDetail"></goodsManagementDetail>
  </div>
</template>
<script>
import SetColumn from '@/pubComponent/SetColumn.vue'
import crumbs from '@/components/crumbs.vue'
import { getNewColumns, subStrText, camelCase2UnderLine, commafyTofixed, formatDate } from '@/utils/util'
import { API } from '@/api/requestFzs'
import { APILX } from '@/api/requestLx'
import moment from 'dayjs'
import { httpAction, getAction, deleteAction, downFile, downFilePost } from '@/api/manage'
import { mapState } from 'vuex'
import { TreeSelect } from 'ant-design-vue'
import { ajaxGetDictItems, getEnableOne } from '@/api/api'
import { goodsList, categoryGetTree, getDictModel } from '@/api/goodsManagement'
import tableDragResize from '@/mixins/tableDragResize'
import { hasButton } from '@/utils/hasPermission'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
const treeData = []
// 表头
let addColumn1 = [
  {
    title: '物品编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'serialNumber',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialNumber',
    },
  },
  {
    title: '物品名称',
    width: 150,
    ellipsis: true,
    dataIndex: 'serialName',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialName',
    },
  },
  {
    title: '规格',
    dataIndex: 'serialSpecifications',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialSpecifications',
    },
  },
  {
    title: '物品属性',
    dataIndex: 'serialProperties',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'serialProperties',
    },
  },
  {
    title: '单位',
    dataIndex: 'serialUnit',
    width: 150,
    ellipsis: true,
    scopedSlots: {
      customRender: 'serialUnit',
    },
  },
  {
    title: '库存数量',
    width: 150,
    sorter: true,
    dataIndex: 'inventoryNum',
    scopedSlots: {
      customRender: 'inventoryNum',
    },
  },
  {
    title: '最小库存',
    width: 150,
    dataIndex: 'inventoryMin',
    scopedSlots: {
      customRender: 'inventoryMin',
    },
  },
]
let addColumn2 = [
  {
    title: '物品编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'serialNumber',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialNumber',
    },
  },
  {
    title: '物品名称',
    width: 150,
    ellipsis: true,
    dataIndex: 'serialName',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialName',
    },
  },
  {
    title: '规格',
    dataIndex: 'serialSpecifications',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialSpecifications',
    },
  },
  {
    title: '物品属性',
    dataIndex: 'serialProperties',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'serialProperties',
    },
  },
  {
    title: '单位',
    dataIndex: 'serialUnit',
    width: 150,
    ellipsis: true,
    scopedSlots: {
      customRender: 'serialUnit',
    },
  },
  {
    title: '库存数量',
    width: 150,
    sorter: true,
    dataIndex: 'inventoryNum',
    scopedSlots: {
      customRender: 'inventoryNum',
    },
  },
  {
    title: '最大库存',
    width: 150,
    dataIndex: 'inventoryMax',
    scopedSlots: {
      customRender: 'inventoryMax',
    },
  },
]
let columnsValue = [
  {
    title: '物品编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'serialNumber',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialNumber',
    },
  },
  {
    title: '物品名称',
    width: 150,
    ellipsis: true,
    dataIndex: 'serialName',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialName',
    },
  },
  {
    title: '规格',
    dataIndex: 'serialSpecifications',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialSpecifications',
    },
  },
  {
    title: '物品属性',
    dataIndex: 'serialProperties',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'serialProperties',
    },
  },
  {
    title: '单位',
    dataIndex: 'serialUnit',
    width: 150,
    ellipsis: true,
    scopedSlots: {
      customRender: 'serialUnit',
    },
  },
  {
    title: '库存数量',
    width: 150,
    sorter: true,
    dataIndex: 'inventoryNum',
    scopedSlots: {
      customRender: 'inventoryNum',
    },
  },
  {
    title: '最小库存',
    width: 150,
    dataIndex: 'inventoryMin',
    scopedSlots: {
      customRender: 'inventoryMin',
    },
  },
]
let columns = [
  {
    title: '物品编号',
    width: 180,
    ellipsis: true,
    dataIndex: 'serialNumber',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialNumber',
    },
  },
  {
    title: '物品名称',
    width: 150,
    ellipsis: true,
    dataIndex: 'serialName',
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialName',
    },
  },
  {
    title: '规格',
    dataIndex: 'serialSpecifications',
    width: 180,
    ellipsis: true,
    scopedSlots: {
      filterDropdown: 'searchInput',
      filterIcon: 'searchIcon',
      customRender: 'serialSpecifications',
    },
  },
  {
    title: '物品属性',
    dataIndex: 'serialProperties',
    ellipsis: true,
    width: 150,
    scopedSlots: {
      filterDropdown: 'selectDropdown',
      filterIcon: 'selectIcon',
      customRender: 'serialProperties',
    },
  },
  {
    title: '单位',
    dataIndex: 'serialUnit',
    width: 150,
    ellipsis: true,
    scopedSlots: {
      customRender: 'serialUnit',
    },
  },
  {
    title: '库存数量',
    width: 150,
    sorter: true,
    dataIndex: 'inventoryNum',
    scopedSlots: {
      customRender: 'inventoryNum',
    },
  },
  {
    title: '最小库存',
    width: 150,
    dataIndex: 'inventoryMin',
    scopedSlots: {
      customRender: 'inventoryMin',
    },
  },
]
// const actionArr = [
//   {
//     fixed: 'right',
//     title: '操作',
//     width: 50,
//     dataIndex: 'actions',
//     ellipsis: true,
//     scopedSlots: { customRender: 'actions' },
//   },
// ]
let startDate = moment().startOf('month').format('YYYY-MM-DD HH:mm:ss')
let endDate = moment().format('YYYY-MM-DD HH:mm:ss')
export default {
  mixins: [tableDragResize],
  data() {
    return {
      getReportList: APILX.wmsReportFormsSecurityPageList,
      selectExportTitle: '',
      selectExportVisiable: false, // 导出弹窗
      selectExportParam: {}, // 导出参数
      filedKeys: '', // 导出字段
      fileName: '', // 导出文件名
      // 树
      treeData,
      SHOW_PARENT,
      treeSelectLael: '',
      replaceFields: {
        children: 'children',
        title: 'name',
        key: 'id',
        value: 'id',
      },
      // 头部按月搜索
      // monthEnd: '',
      // monthStart: '',
      now: null,
      // 头部配置
      topArray: [
        {
          title: '预警物品种类',
          number: '0',
        },
        {
          title: '物品差额数',
          number: '0',
        },
      ],

      typeList: [], //类型 字典值下拉数据
      dictOptionsDeviceCategory: [], //设备类别字典值下拉数据
      commafyTofixed,
      moment,
      selectedRowKeys: [],
      selectedRows: [],
      subStrText,
      showFilter: false, // 筛选抽屉
      modelList: [], // 列表数据
      showSetColumn: false, // 显示
      //全选按钮
      listIndeterminate: false,
      listCheckAll: false,
      current: 1,
      total: 0,
      pageSize: 30,
      pageSizeOptions: ['10', '20', '30', '40', '50'],
      columnsValue,
      columns,
      filterForm: {
        serialNumber: '',
        serialName: '',
        serialSpecifications: '',
        serialProperties: undefined,
        createTime: [startDate, endDate],
        startTime: startDate,
        endTime: endDate,
        type: '0', //类型
        // category: [], //分类
      },
      inOutDate: null,
      filteredFormLable: {
        serialNumber: '物品编号',
        serialName: '物品名称',
        serialSpecifications: '规格',
        serialProperties: '物品属性',
        createTime: '创建日期',
        type: '预警类型',
        // category: '分类',
        //
      },
      sortForm: {
        sortType: '',
        sortColumn: '',
      },
      dateForm: {
        createTime: [startDate, endDate],
        // inOutDate: null,
      } /* 筛选日期绑定对象 */,
      customSelectList: [],
      applyStatusList: [],
      dealStatusList: [],
      serialPropertiesList: [
        { label: '自制', value: '0' },
        { label: '外购', value: '1' },
      ],
      loginUser: '',
      typeString: '库存不足',
      tableKey: 1.9,
    }
  },
  watch: {
    'filterForm.type': {
      handler(newVal) {
        if (newVal == '0') {
          this.columns = addColumn1
          this.columnsValue = addColumn1
        } else {
          this.columns = addColumn2
          this.columnsValue = addColumn2
        }
      },
      deep: true,
    },
  },
  components: {
    SetColumn,
    crumbs,
    goodsManagementDetail: (resolve) => require(['@/views/baseManagement/goodsManagement/detail'], resolve),
  },
  computed: {
    scrollX() {
      let xnum = 0
      for (let item of this.columns) {
        xnum += Number(item.width) || 0
      }
      return xnum
    },
    ...mapState({
      collapsed: (state) => state.user.collapsedAno,
    }),
    filteredList() {
      let list = []
      for (let key in this.filterForm) {
        if (this.filteredFormLable[key] == '类型') {
          console.log('类型', this.typeList)
          let strArr = ''
          for (let item of this.filterForm[key]) {
            for (let each of this.typeList) {
              if (item == each.value) {
                strArr += each.title + '，'
              }
            }
          }
          strArr = strArr.substring(0, strArr.length - 1)
          list.push({
            title: this.filteredFormLable[key],
            text: strArr,
            key,
          })
        } else if (this.filteredFormLable[key] == '分类' && key == 'category') {
          console.log('分类')
          list.push({
            title: this.filteredFormLable[key],
            text: this.treeSelectLael,
            key,
          })
        } else if (this.filteredFormLable[key] == '预警类型' && key == 'type') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.typeString,
            key,
          })
        } else if (key == 'reporter') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.userNames,
            key,
          })
        } else if (key == 'createTime') {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm.startTime
              ? moment(this.filterForm.startTime).format('YYYY-MM-DD') +
                '-' +
                moment(this.filterForm.endTime).format('YYYY-MM-DD')
              : '',
            key,
          })
        } else if (key == 'startTime' || key == 'endTime') {
          // 什么都不干
        } else if (key == 'serialProperties' && this.filterForm[key]) {
          list.push({
            title: this.filteredFormLable[key],
            text: this.statusToTxt(key, this.filterForm[key]),
            key,
          })
        } else {
          list.push({
            title: this.filteredFormLable[key],
            text: this.filterForm[key],
            key,
          })
        }
      }
      return list
    },
    filteredNums() {
      let nums = 1
      for (let key in this.filterForm) {
        if (this.filterForm[key] != '' && this.filterForm[key] != null && this.filterForm[key] != undefined) {
          // nums += 1
          if (key != 'type') {
            nums += 1
            if (key == 'startTime') {
              nums -= 2
            }
          }
          // if (key == 'startTime') {
          //   nums -= 1
          // }
        }
        // if (key == 'type') {
        //   nums += 1
        // }
      }
      return nums
    },
  },
  created() {
    let user = localStorage.getItem('pro__Login_Userinfo')
    this.loginUser = JSON.parse(user).value.id
    // this.initData()
    // this.now = moment().locale('zh-cn').format('YYYY-MM')
    // this.monthStart = moment(this.now).startOf('month').format('YYYY-MM-DD HH:mm:ss')
    // this.monthEnd = moment(this.now).endOf('month').format('YYYY-MM-DD HH:mm:ss')
    // this.inOutDate = this.now
    // console.log(this.monthStart, this.monthEnd, this.now, 'monthStart')
    // this.filterForm[`startDate`] = this.monthStart
    // this.filterForm[`endDate`] = moment().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss')
    // this.filterForm[`inOutDate`] = moment().locale('zh-cn').format('YYYY-MM')
    this.requestData()
  },
  methods: {
    hasButton,
    changeGetList(v) {
      this.filterForm.type = v
      this.typeString = v == 0 ? '库存不足' : '库存超量'
      this.handleSearch()
      return
      if (v == '0') {
        this.getReportList = APILX.wmsReportFormsSecurityPageList
      } else {
        this.getReportList = APILX.wmsReportFormsMaxPageList
      }
      this.handleSearch()
    },
    treeChange(value, label, extra) {
      this.treeSelectLael = label[0]
    },
    // 限制开始日期
    disabledStartDate(startValue) {
      let date = new Date(new Date().getTime())
      return date.valueOf() <= startValue.valueOf()
    },
    // 导出
    handleExport(e) {
      let that = this
      // 获取动态列
      let filedKeysList = []
      that.columns.forEach((item) => {
        if (item.dataIndex == 'category') {
          item.dataIndex = 'categoryText'
        }
        filedKeysList.push(item.dataIndex)
      })
      // filedKeysList.pop()//删除最后一个的操作列
      that.filedKeys = filedKeysList.join(',')
      //设置文件名
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      let day = date.getDate()
      let time = `${year}-${month}-${day}`
      if (that.filterForm.startTime) {
        that.fileName = `${formatDate(that.filterForm.startTime, 'YYYY-MM-DD')}~${formatDate(
          that.filterForm.endTime,
          'YYYY-MM-DD'
        )} 库存水位预警表`
      } else {
        that.fileName = '库存水位预警表'
      }
      if (!e || e.length === 0) {
        that.handleExportAll()
        that.selectExportVisiable = false
      } else {
        that.selectExportTitle = `已选中${e.length}条数据`
        that.selectExportVisiable = true
        that.selectExportParam = {
          ...that.queryParam,
          selectedList: e,
          fileName: that.fileName, //文件名
          filedKeys: that.filedKeys, //动态列
          warnType: that.getReportList == APILX.wmsReportFormsSecurityPageList ? 'security_inventory' : 'max_inventory',
        }
      }
    },
    handleSelectExport() {
      this.selectExportVisiable = false
      downFilePost('/report/serialAlert/exportWaterWarningXls', this.selectExportParam).then((data) => {
        if (data.type == 'application/json') {
          const reader = new FileReader() //创建一个FileReader实例
          reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
          reader.onload = function () {
            //读取完成后,**获取reader.result**
            const msg = JSON.parse(reader.result)
            this.$antdMessage.error(msg.message) //弹出错误提示
          }
          return
        }
        if (!data) {
          this.$antdMessage.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), this.fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', this.fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleExportAll() {
      let that = this
      that.selectExportVisiable = false
      that.$antdConfirm({
        title: `导出`,
        content: `确定全部数据?`,
        onOk() {
          let param = {
            ...that.filterForm,
            ...that.sortForm,
            fileName: that.fileName,
            filedKeys: that.filedKeys,
            warnType:
              that.getReportList == APILX.wmsReportFormsSecurityPageList ? 'security_inventory' : 'max_inventory',
          }
          // 删除param中的空子段
          for (let key in param) {
            if (param[key] == '' || param[key] == null || param[key] == undefined || param[key] == []) {
              delete param[key]
            }
          }
          console.log(param, '导出选中数据param')
          downFilePost('/report/serialAlert/exportWaterWarningXls', param).then((data) => {
            if (data.type == 'application/json') {
              const reader = new FileReader() //创建一个FileReader实例
              reader.readAsText(data, 'utf-8') //读取文件,结果用字符串形式表示
              reader.onload = function () {
                //读取完成后,**获取reader.result**
                const msg = JSON.parse(reader.result)
                that.$antdMessage.error(msg.message) //弹出错误提示
              }
              return
            }
            if (!data) {
              that.$antdMessage.warning('文件下载失败')
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data]), that.fileName + '.xls')
            } else {
              let url = window.URL.createObjectURL(new Blob([data]))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', that.fileName + '.xls')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
            }
          })
        },
        onCancel() {},
      })
    },

    handleOpen(v, status) {
      let that = this
      let title = status == '0' ? '启用' : '禁用'
      that.$antdConfirm({
        title: `确定${title}此点巡检方案吗?`,
        // content: `共选中${v.length}条点巡检项目`,
        onOk() {
          let param = {
            id: v.id,
            status: status,
          }
          APILX.deviceCheckProgramUpdateStatus(param).then((res) => {
            if (res.code == 200) {
              that.$antdMessage.success('操作成功')
              that.handleSearch()
            } else {
              that.$antdMessage.error(res.message)
            }
          })
        },
        onCancel() {},
      })
    },
    changeSelect(v, key) {
      if (v.length == 0 || v == '' || v == undefined) {
        // this.filterForm[key] = undefined
        this.filterForm[key] = []
      }
    },
    selectkeys(key) {
      if (key == 'typeText') {
        return 'type'
      } else if (key == 'category') {
        return 'category'
      }
    },
    selectOptions(key) {
      if (key == 'deviceCategoryText') {
        return this.dictOptionsDeviceCategory
      } else if (key == 'flowStatusText') {
        return this.applyStatusList
      } else if (key == 'typeText') {
        return this.typeList
      }
    },
    /* 筛选类型回显文字 */
    statusToTxt(key, val) {
      var valList = []
      if (key == 'serialProperties' && this.filterForm[key]) {
        for (let i = 0; i < val.length; i++) {
          const item = val[i]
          for (let j = 0; j < this.serialPropertiesList.length; j++) {
            const txt = this.serialPropertiesList[j]
            if (item == txt.value) {
              valList.push(txt.label)
            }
          }
        }
        return valList.join(',')
      } else if (key == 'deviceCategory' && this.filterForm[key]) {
        for (let i = 0; i < val.length; i++) {
          const item = val[i]
          for (let j = 0; j < this.dictOptionsDeviceCategory.length; j++) {
            const txt = this.dictOptionsDeviceCategory[j]
            if (item == txt.value) {
              valList.push(txt.title)
            }
          }
        }
        return valList.join(',')
      }
    },
    /* 类型颜色 */
    taskStatusCheck(v) {
      let checked = false
      if (v == '0') {
        checked = false
      } else if (v == '1') {
        checked = true
      }
      return checked ? '#ff943e' : '#00b042'
    },
    /* 日期选择 */
    onOk(value, key) {
      if (value.length == 0) {
        this.filterForm[`startTime`] = ''
        this.filterForm[`endTime`] = ''
        this.filterForm[key] = ''
        return
      }
      this.filterForm[`startTime`] = moment(value[0]).startOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.filterForm[`endTime`] = moment(value[1]).endOf('day').format('YYYY-MM-DD HH:mm:ss')
      this.handleSearch()
    },

    // 排序
    tableChange(pagination, filters, sorter, { currentDataSource }) {
      console.log('看看这是啥33：', sorter)
      if (sorter.order) {
        let sortType = ''
        if (sorter.order == 'ascend') {
          sortType = 'ASC'
        } else {
          sortType = 'DESC'
        }
        this.sortForm = {
          sortType: sortType,
          sortColumn: sorter.columnKey,
        }
        this.requestData()
      } else {
        this.sortForm = {
          sortType: '',
          sortColumn: '',
        }
        this.requestData()
      }
    },
    // table选择
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
      this.checkBoxStatus()
    },
    // 全选
    // onCheckAllChange(e) {
    //   if (e.target.checked) {
    //     for (let item of this.modelList) {
    //       this.selectedRowKeys.push(item.goodsId)
    //     }
    //   } else {
    //     for (let item of this.modelList) {
    //       this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
    //         return each != item.goodsId
    //       })
    //     }
    //   }
    //   this.checkBoxStatus()
    // },
    // 全选
    onCheckAllChange(e) {
      if (e.target.checked) {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.goodsId
          })
          this.selectedRowKeys.push(item.goodsId)
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.goodsId != item.goodsId
          })
          this.selectedRows.push(item)
        }
      } else {
        for (let item of this.modelList) {
          this.selectedRowKeys = this.selectedRowKeys.filter((each) => {
            return each != item.goodsId
          })
          this.selectedRows = this.selectedRows.filter((each) => {
            return each.goodsId != item.goodsId
          })
        }
      }
      this.checkBoxStatus()
    },
    // 清空
    clearArr() {
      this.selectedRowKeys = []
      this.selectedRows = []
      this.checkBoxStatus()
    },
    checkBoxStatus() {
      if (this.selectedRowKeys.length == 0) {
        this.listIndeterminate = false
        this.listCheckAll = false
      } else {
        let tableIds = []
        for (let item of this.modelList) {
          tableIds.push(item.goodsId)
        }
        let checkValue = this.isInclude(tableIds, this.selectedRowKeys)
        if (checkValue) {
          this.listIndeterminate = false
          this.listCheckAll = true
        } else {
          this.listIndeterminate = true
          this.listCheckAll = false
        }
      }
    },
    isInclude(aa, bb) {
      return aa.every((item) => {
        return bb.some((sub) => {
          return sub === item
        })
      })
    },
    // 分页
    onChangePage(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    onShowSizeChange(current, pageSize) {
      this.current = current
      this.pageSize = pageSize
      this.requestData(true)
    },
    handleSearch(selectedKeys, confirm, dataIndex, clearFilters) {
      this.current = 1
      this.requestData()
    },
    /* 打开筛选 */
    handleShowFilter() {
      this.showFilter = true
    },
    /* 关闭筛选 */
    closeFilter() {
      this.showFilter = false
    },
    /* 确定筛选 */
    handleFilter() {
      this.handleSearch()
      this.showFilter = false
    },
    /* 删除已选 */
    delFiltered(key) {
      if (key == 'serialNumber') {
        this.filterForm[key] = ''
      } else if (this.filteredFormLable[key] == '创建日期') {
        this.filterForm.startTime = ''
        this.filterForm.endTime = ''
        this.filterForm[key] = ''
        this.dateForm[key] = null
      } else if (this.filteredFormLable[key] == '物品名称') {
        this.filterForm[key] = ''
      } else if (this.filteredFormLable[key] == '分类') {
        this.filterForm[key] = []
        this.treeSelectLael = ''
      } else if (this.filteredFormLable[key] == '类型') {
        this.filterForm[key] = []
      } else if (this.filteredFormLable[key] == '出入库日期') {
      } else if (key == 'programStatus' || key == 'deviceCategory') {
        this.filterForm[key] = undefined
      } else if (key == 'startTime') {
      } else if (key == 'endDate') {
      } else {
        this.filterForm[key] = ''
      }
    },
    /* 重置筛选 */
    resetFilter() {
      this.filterForm = {
        serialNumber: '',
        serialName: '',
        serialSpecifications: '',
        serialProperties: undefined,
        createTime: '',
        startTime: '',
        endTime: '',
        type: '0', //类型
      }
      this.dateForm = {
        createTime: '',
      }
      this.treeSelectLael = ''
      this.handleSearch()
    },
    /* 初始/加载设置列 */
    initData() {
      var oldValue = localStorage.getItem(this.BUSI_CONST.Entity.WATER_LEVEL_REPORT)
      this.columns = getNewColumns(this.columnsValue, JSON.parse(oldValue), [], this.columns)
      /* 客户下拉 */
      API.erpCustomerList({ pageSize: 999, pageNo: 1 }).then((res) => {
        if (res.code == 200) {
          this.customSelectList = res.result.records
        }
      })
      ajaxGetDictItems('erp_apply_status').then((res) => {
        if (res.result) {
          this.applyStatusList = res.result
        }
      })
      ajaxGetDictItems('erp_contract_status').then((res) => {
        if (res.result) {
          this.dealStatusList = res.result
        }
      })
      // 字典接口
      getDictModel({ dictCode: 'mess_device_category' }).then((res) => {
        this.dictOptionsDeviceCategory = res.result
      })
      // 字典接口 类型
      getDictModel({ dictCode: 'wms_goods_type' }).then((res) => {
        this.typeList = res.result
      })
      this.getTreeData()
    },
    getTreeData() {
      // 取分类树
      categoryGetTree({ code: 'B05' }).then((res) => {
        let arr = res.result
        arr.map((item) => {
          if (item.children.length > 0) {
            item.disabled = true
            ;(function bianli(e = item) {
              e.children.forEach((item) => {
                if (item.children.length > 0) {
                  item.disabled = true
                  bianli(item)
                }
              })
            })()
          }
        })
        this.treeData = arr
      })
    },
    /* 请求列表数据 */
    requestData(check) {
      if (this.filterForm.endTime) {
        this.filterForm.endTime = moment(this.filterForm.endTime).format('YYYY-MM-DD') + ' ' + '23:59:59'
      }
      let parameter = {
        pageNo: this.current,
        pageSize: this.pageSize,
        month: '',
        ...this.filterForm,
        ...this.sortForm,
      }
      if (parameter.deviceCategory) {
        parameter.deviceCategory = parameter.deviceCategory.join(',')
      }

      if (parameter.serialProperties) {
        parameter.serialProperties = parameter.serialProperties.join(',')
      }
      delete parameter.createTime
      APILX.getSerialAlertList(parameter).then((res) => {
        if (res.code == 200) {
          if (res.result.page.total) {
            this.total = res.result.page.total
          } else {
            this.total = 0
          }
          this.initDataTop(res.result)
          this.modelList = res.result.page.records
          if (check) {
            this.checkBoxStatus()
          }
        }
      })
    },
    initDataTop(v) {
      if (v) {
        this.topArray[0].number = v.serialTypeCount || '0'
        this.topArray[1].number = v.serialCount || '0'
      }
    },
    /* 打开设置列面板 */
    showColumn() {
      this.showSetColumn = true
      this.$nextTick(() => {
        this.$refs.SetColumn.paramsData(this.columnsValue, this.BUSI_CONST.Entity.WATER_LEVEL_REPORT, this.columns)
      })
    },
    /* 设置列 */
    sureBtn(emitArr) {
      this.columns = getNewColumns(this.columnsValue, emitArr, [])
      console.log(this.columns)
      localStorage.setItem(this.BUSI_CONST.Entity.WATER_LEVEL_REPORT, JSON.stringify(emitArr))
      this.tableKey += 1
    },
    /* 新建 */
    handleAdd() {
      this.$openWay(this, true, '/inserialSpecificationstionProgramForm')
    },
    /* 编辑 */
    handleEdit(v) {
      this.$openWay(this, true, '/inserialSpecificationstionProgramForm', { id: v.id })
    },
    /* 详情 */
    handleDetail(v) {
      this.$refs.goodsManagementDetail.initDetail(v.id)
    },
    /* 删除、批量删除 */
    handleDelete(v) {
      if (v instanceof Array) {
        if (v.length > 0) {
          let that = this
          that.$antdConfirm({
            title: '确定要删除点巡检方案吗?',
            content: `共选中${v.length}条点巡检方案`,
            onOk() {
              APILX.messDeviceCheckProgramDeleteBatch(v.toString()).then((res) => {
                if (res.code == 200) {
                  that.$antdMessage.success('删除成功！')
                  that.handleSearch()
                  that.clearArr()
                } else {
                  that.$antdMessage.error(res.message)
                }
              })
            },
            onCancel() {},
          })
        } else {
          this.$antdMessage.warning('请勾选需要批量删除的数据')
        }
      } else {
        let that = this
        that.$antdConfirm({
          title: '确定要删除此点巡检方案吗?',
          content: ``,
          onOk() {
            APILX.messDeviceCheckProgramDelete(v.id).then((res) => {
              if (res.code == 200) {
                that.$antdMessage.success('删除成功！')
                that.handleSearch()
                that.clearArr()
              } else {
                that.$antdMessage.error(res.message)
              }
            })
          },
          onCancel() {},
        })
      }
    },
    //点击返回按钮
    goBack() {
      console.log('goback')
    },
  },
}
</script>
<style scoped lang="less">
@import '~@/assets/less/public.less';
// @import '~@assets/less/common.less';
.flex(@jc,@ai,@fd:row) {
  display: flex;
  justify-content: @jc;
  align-items: @ai;
  flex-direction: @fd;
}
.header {
  width: 150%;
  margin: -12px -12px @distance4;
}
.backBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .backC {
    cursor: pointer;
    display: flex;
    align-items: center;
  }
}
.j-table-force-nowrap {
  margin-top: @distance1;
}
.btns {
  margin-left: @distance5;
}
.right-btn {
  // float: right;
  // display: flex;
  // justify-content: flex-end;
}
.mg-left {
  margin-left: @distance3;
}
.filter-tit {
  background: #fff;
  border-bottom: 1px solid @greyBorder;
  font-size: @fontSize4;
}
.filter-num {
  color: @normalFont;
}
.filter-body {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.margin-btn {
  margin-right: @distance5;
}
.filter-tag {
  display: inline-block;
  position: relative;
  padding: 8px 10px;
  border-radius: 4px;
  font-size: @fontSize1;
  line-height: @fontSize1;
  max-width: 100%;
  background: @greyBg;
  color: @titFont;
  cursor: pointer;
  .tag-text {
    display: inline-block;
    padding-right: 20px;
    max-width: 100%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .anticon-close {
    position: absolute;
    right: 8px;
    top: 8px;
  }
}
.tag-wrap:nth-of-type(n + 2) {
  margin-top: 10px;
}
.searchWorkOreder {
  .flex(flex-start, center);
  padding: 8px;
}
/deep/ .ant-card-body {
  // height: calc(100vh - 214px);
  // overflow: hidden;
  padding: 20px 16px;
}
.pubColor {
  font-size: 14px;
  color: #1890ff;
  cursor: pointer;
}

div.topBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // margin-bottom: 16px;
  box-sizing: border-box;
  padding: 23px 0;
  background: #fff;
  div.itemBox {
    display: flex;
    justify-content: center;
    align-items: center;
    flex: 1;
    box-sizing: border-box;
    height: 44px;
    padding: 0px 60px;
    position: relative;
    border-right: 1px solid #eeeeee;

    div.rightBox {
      text-align: center;
      height: 44px;
      cursor: pointer;
      display: flex;
      align-items: flex-start;
      flex-direction: column;
      justify-content: flex-start;
      margin-left: 16px;
      div.rightTop {
        font-size: 24px;
        color: #191f25;
        line-height: 24px;
        margin-top: 12px;
      }

      div.rightBot {
        font-size: 14px;
        color: #888888;
      }
    }
  }
}
.topBox .itemBox:last-child {
  border: none;
}
.topSearch {
  padding: 0 0 10px 38px;
}
.table-operator .ant-btn {
  margin: 0 8px -4px 0;
}
/deep/ .ant-modal-footer {
  .ant-btn {
    width: 116px;
  }
}
</style>
